package com.geekai.chat.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.geekai.chat.common.Result;
import com.geekai.chat.dto.LoginRequest;
import com.geekai.chat.dto.LoginResponse;
import com.geekai.chat.entity.Conversation;
import com.geekai.chat.entity.User;
import com.geekai.chat.service.AdminService;
import com.geekai.chat.service.ConversationService;
import com.geekai.chat.service.MessageService;
import com.geekai.chat.service.UserService;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/admin")
@RequiredArgsConstructor
public class AdminController {

    private final AdminService adminService;
    private final UserService userService;
    private final ConversationService conversationService;
    private final MessageService messageService;

    @PostMapping("/auth/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = adminService.login(loginRequest);
            return Result.success(response);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/dashboard")
    public Result<Map<String, Object>> getDashboard() {
        try {
            Map<String, Object> dashboard = new HashMap<>();
            
            // 统计数据
            long userCount = userService.count();
            long conversationCount = conversationService.count();
            long messageCount = messageService.count();
            
            dashboard.put("userCount", userCount);
            dashboard.put("conversationCount", conversationCount);
            dashboard.put("messageCount", messageCount);
            
            // 最近用户
            QueryWrapper<User> userWrapper = new QueryWrapper<>();
            userWrapper.orderByDesc("create_time").last("LIMIT 5");
            List<User> recentUsers = userService.list(userWrapper);
            dashboard.put("recentUsers", recentUsers);
            
            // 最近对话
            QueryWrapper<Conversation> conversationWrapper = new QueryWrapper<>();
            conversationWrapper.orderByDesc("create_time").last("LIMIT 5");
            List<Conversation> recentConversations = conversationService.list(conversationWrapper);
            dashboard.put("recentConversations", recentConversations);
            
            return Result.success(dashboard);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/users")
    public Result<com.baomidou.mybatisplus.extension.plugins.pagination.Page<User>> getUsers(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {
        try {
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<User> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size);
            QueryWrapper<User> wrapper = new QueryWrapper<>();

            if (keyword != null && !keyword.trim().isEmpty()) {
                wrapper.like("username", keyword)
                        .or().like("email", keyword)
                        .or().like("nickname", keyword);
            }

            wrapper.orderByDesc("create_time");
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<User> userPage = userService.page(page, wrapper);

            return Result.success(userPage);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PutMapping("/users/{userId}/status")
    public Result<Void> updateUserStatus(@PathVariable Long userId, @RequestParam Integer status) {
        try {
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            user.setStatus(status);
            userService.updateById(user);

            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping("/users/{userId}")
    public Result<Void> deleteUser(@PathVariable Long userId) {
        try {
            userService.removeById(userId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/conversations")
    public Result<com.baomidou.mybatisplus.extension.plugins.pagination.Page<Conversation>> getConversations(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {
        try {
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Conversation> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size);
            QueryWrapper<Conversation> wrapper = new QueryWrapper<>();

            if (keyword != null && !keyword.trim().isEmpty()) {
                wrapper.like("title", keyword);
            }

            wrapper.orderByDesc("create_time");
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Conversation> conversationPage = conversationService.page(page, wrapper);

            return Result.success(conversationPage);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/conversations/{conversationId}/messages")
    public Result<java.util.List<com.geekai.chat.dto.MessageDto>> getConversationMessages(@PathVariable Long conversationId) {
        try {
            java.util.List<com.geekai.chat.dto.MessageDto> messages = messageService.getConversationMessages(conversationId);
            return Result.success(messages);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping("/conversations/{conversationId}")
    public Result<Void> deleteConversation(@PathVariable Long conversationId) {
        try {
            conversationService.removeById(conversationId);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}